package workexp

import (
	"context"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"wh-1-backend/internal/dao"
	"wh-1-backend/internal/model"
	"wh-1-backend/internal/model/do"
	"wh-1-backend/internal/model/entity"
	"wh-1-backend/internal/service"
)

type sWorkExp struct{}

func New() *sWorkExp {
	return &sWorkExp{}
}

func init() {
	service.RegisterWorkExp(New())
}

func (w *sWorkExp) Insert(ctx context.Context, list []*model.EditWorkExperienceInput) (err error) {
	data := make([]*do.WorkExperience, 0, 8)
	for _, input := range list {
		data = append(data, &do.WorkExperience{
			ResumeId:  input.ResumeId,
			From:      input.From,
			End:       input.End,
			CompanyId: input.CompanyId,
			Remarks:   input.Remarks,
		})
	}
	_, err = dao.WorkExperience.Ctx(ctx).Insert(data)
	return
}

func (w *sWorkExp) GetByResumeId(ctx context.Context, resumeId uint) (res []*entity.WorkExperience, err error) {
	res = []*entity.WorkExperience{}
	err = dao.WorkExperience.Ctx(ctx).Where(dao.WorkExperience.Columns().ResumeId, resumeId).Scan(&res)
	return
}

func (w *sWorkExp) UpdateByResumeId(ctx context.Context, resumeId uint, list []*model.EditWorkExperienceInput) (err error) {
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		_, err2 := dao.WorkExperience.Ctx(ctx).Where(dao.WorkExperience.Columns().ResumeId, resumeId).Delete()
		if err2 != nil {
			return err2
		}
		if list == nil || len(list) == 0 {
			return nil
		} else {
			err2 = w.Insert(ctx, list)
		}
		return err2
	})
	return
}
